package com.margo.project.curator.discovery;

import java.io.Closeable;
import java.io.IOException;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.UriSpec;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;

public class MargoZookeeperServer implements Closeable{
    private final ServiceDiscovery<MargoInstanceDetails> serviceDiscovery;
    private final ServiceInstance<MargoInstanceDetails> thisInstance;

    public MargoZookeeperServer(CuratorFramework client, String path, String serviceName, String description) throws Exception
    {
        // in a real application, you'd have a convention of some kind for the URI layout
        UriSpec     uriSpec = new UriSpec("{scheme}://foo.com:{port}");

        thisInstance = ServiceInstance.<MargoInstanceDetails>builder()
            .name(serviceName)
            .payload(new MargoInstanceDetails(description))
            .port((int)(65535 * Math.random())) // in a real application, you'd use a common port
            .uriSpec(uriSpec)
            .build();

        // if you mark your payload class with @JsonRootName the provided JsonInstanceSerializer will work
        JsonInstanceSerializer<MargoInstanceDetails> serializer = new JsonInstanceSerializer<MargoInstanceDetails>(MargoInstanceDetails.class);

        serviceDiscovery = ServiceDiscoveryBuilder.builder(MargoInstanceDetails.class)
            .client(client)
            .basePath(path)
            .serializer(serializer)
            .thisInstance(thisInstance)
            .build();
    }

    public ServiceInstance<MargoInstanceDetails> getThisInstance()
    {
        return thisInstance;
    }

    public void start() throws Exception
    {
        serviceDiscovery.start();
    }

    public void close() throws IOException
    {
        CloseableUtils.closeQuietly(serviceDiscovery);
    }

}
